# -*- coding:utf-8 -*-
import web, service, os
from baseHandler import BaseHandler

BUF_SIZE = 1024 * 1024

downloadFileTypeTable = {
    'finished_cases' : u'已结案件清单',
    'unfinished_cases' : u'未结案件清单'
}

class CompanyCasesExcel(BaseHandler):
    def GET(self, branchCompanyId, _type):
        user = self.getCurrentUser()
        branchCompanyId = long(branchCompanyId)
        service.Company.getBranchCompany(branchCompanyId)
        hasOverviewRight = service.User.hasOverviewRight(user)

        branchCompany = service.Company.getBranchCompany(branchCompanyId)

        if not hasOverviewRight and branchCompanyId != user.company_id:
            raise web.seeother('/company/%d/%s/excel' % (user.company_id, _type))

        if 'finished_cases' == _type:
            filename = service.Excel.getFinishedCasesExcelPath(branchCompanyId)
        elif 'unfinished_cases' == _type:
            filename = service.Excel.getUnfinishedCasesExcelPath(branchCompanyId)
        try:
            f = open(filename, "rb")
            web.header('Content-Type','application/octet-stream')
            web.header('Content-disposition', 'attachment; filename=%s%s.xls' % (branchCompany.name, downloadFileTypeTable[_type]))
            while True:
                c = f.read(BUF_SIZE)
                if c:
                    yield c
                else:
                    break
        finally:
            f and f.close()
        os.remove(filename)


